package com.ruoyi.business.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.business.domain.Degrees;
import com.ruoyi.business.domain.Employee;
import com.ruoyi.business.domain.model.CheckDegreeHis;
import com.ruoyi.business.domain.vo.DormitoryVo;
import com.ruoyi.common.utils.poi.ExcelUtilPlus;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.business.domain.vo.DegreesVo;
import com.ruoyi.business.domain.bo.DegreesBo;
import com.ruoyi.business.service.IDegreesService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 宿舍电度数
 *
 * @author ruoyi
 * @date 2023-06-28
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/business/degrees")
public class DegreesController extends BaseController {

    private final IDegreesService iDegreesService;

    /**
     * 查询宿舍电度数列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Degrees entity) {
        startPage();
        List<Degrees> list = iDegreesService.getList(entity);
        return getDataTable(list);
    }
    /**
     * 查询宿舍电度数列表
     */
    @GetMapping("/listHisDegrees")
    public TableDataInfo listHisDegrees(Degrees entity) {
        startPage();
        LambdaQueryWrapper<Degrees> lambdaQueryWrapper=new LambdaQueryWrapper<Degrees>();
        lambdaQueryWrapper.eq(Degrees::getDormitoryid,entity.getDormitoryid());
        lambdaQueryWrapper.orderByDesc(Degrees::getReadDate);
        List<Degrees> list = iDegreesService.list(lambdaQueryWrapper);
        return getDataTable(list);
    }
    /**
     * 导出宿舍电度数列表
     */
    @Log(title = "宿舍电度数", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(Degrees entity, HttpServletResponse response) {
        List<Degrees> list = iDegreesService.getList(entity);
        // 格式化日期字段
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 根据你的需求定义日期格式
        for (Degrees deg:list) {
            if (deg.getReadDate()!=null){
                String formattedDate = dateFormat.format(deg.getReadDate());
                deg.setExcelreadDate(formattedDate);

            }  if (deg.getLastReadDate()!=null){
                String formattedDate = dateFormat.format(deg.getLastReadDate());
                deg.setExcellastReadDate(formattedDate);
            }
        }
        ExcelUtilPlus<Degrees> util = new ExcelUtilPlus<Degrees>(Degrees.class);
        util.exportExcel(response, list, "用电");

    }
    // 获取楼栋列表
    private static List<String> getBuilds(List<Degrees> data) {
        List<String> builds = new ArrayList<>();
        for (Degrees entry : data) {
            if (!builds.contains(entry.getBuildingName())) {
                builds.add(entry.getBuildingName());
            }
        }
        return builds;
    }
    // 获取楼层列表
    private static List<Integer> getFloors(List<Degrees> data) {
        List<Integer> floors = new ArrayList<>();
        for (Degrees entry : data) {
            if (!floors.contains(entry.getFloor())) {
                floors.add(entry.getFloor());
            }
        }
        return floors;
    }
    /**
     * 获取宿舍电度数详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<Degrees> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iDegreesService.getById(id));
    }

    /**
     * 新增宿舍电度数
     */
    @Log(title = "宿舍电度数", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody Degrees bo) {
        if (iDegreesService.save(bo)){
            countDifference(bo.getDormitoryid());
        }
        return toAjax(true);

    }

    /**
     * 修改宿舍电度数
     */
    @Log(title = "宿舍电度数", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody Degrees bo) {
        bo.setRemark("被修改");
        if (iDegreesService.updateById(bo)){
            countDifference(bo.getDormitoryid());
        }
        return toAjax(true);
    }

    /**
     * 删除宿舍电度数
     *
     * @param ids 主键串
     */
    @Log(title = "宿舍电度数", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        Long id=ids[0];
        iDegreesService.del(id);
        return toAjax(true);
    }
    /**
     * 计算2条最近记录的差值
     *
     */
    private void countDifference(Long dormitoryid){
        LambdaQueryWrapper<Degrees> lambdaQueryWrapper=new LambdaQueryWrapper<Degrees>();
        lambdaQueryWrapper.eq(Degrees::getDormitoryid,dormitoryid);
        lambdaQueryWrapper.orderByDesc(Degrees::getReadDate);
        lambdaQueryWrapper.last(" limit 2");
        List<Degrees> list = iDegreesService.list(lambdaQueryWrapper);
        if (list.size()==2){
            Degrees  degreesLast=list.get(0);//最新的一条数据
            Degrees  degrees2=list.get(1);//上次抄表的数据
            Integer degrees2_Numberdegrees=degrees2.getNumberdegrees();
            Integer degreeslast_Numberdegrees=degreesLast.getNumberdegrees();
            degreesLast.setDifference(degreeslast_Numberdegrees-degrees2_Numberdegrees);
            degreesLast.setLastReadDate(degrees2.getReadDate());
            iDegreesService.updateById(degreesLast);
        }

    }
}
